package 笔试;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class 最接近二叉搜索树的值 {

    private List<Integer> list = new ArrayList<>();
    private void inonder(TreeNode root) {
        if(root == null) {
            return;
        }
        inonder(root.left);
        list.add(root.val);
        inonder(root.right);
    }
    public int closestValue(TreeNode root, double target) {

        inonder(root);
        return Collections.min(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Math.abs(o1-target) < Math.abs(o2-target) ? -1 : 1;
            }
        });
    }

    public int closestValue1(TreeNode root, double target) {
        int val, closest = root.val;
        while (root != null) {
            val = root.val;
            closest = Math.abs(val - target) < Math.abs(closest - target) ? val : closest;
            root =  target < root.val ? root.left : root.right;
        }
        return closest;
    }

}
